package net.ruixin.coordinate;

import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;

import java.io.File;
import java.io.FileInputStream;

class TextUtil {

    static String getTextOfFile(String filePath) {
        String text = "";
        File file = new File(filePath);
        if (!file.isFile()) {
            return text;
        }
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if ("PDF".equalsIgnoreCase(suffix)) {
            try {
                RandomAccessRead randomAccessRead = new RandomAccessBufferedFileInputStream(new FileInputStream(file));
                PDFParser pdfParser = new PDFParser(randomAccessRead);
                pdfParser.parse();
                try (PDDocument pdDocument = pdfParser.getPDDocument()) {
                    PDFTextStripper pdfTextStripper = new PDFTextStripper();
                    text = pdfTextStripper.getText(pdDocument);
                }
            } catch (Exception e) {
                return text;
            }
        } else if ("DOCX".equalsIgnoreCase(suffix)) {
            try (XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(OPCPackage.open(file))) {
                text = xwpfWordExtractor.getText();
            } catch (Exception e) {
                return text;
            }
        } else if ("DOC".equalsIgnoreCase(suffix)) {
            try (WordExtractor wordExtractor = new WordExtractor(new FileInputStream(file))) {
                text = wordExtractor.getText();
            } catch (Exception e) {
                return text;
            }
        } else {
            return text;
        }
        return text;
    }
}
